//
//  giftListDataBase.m
//  tcpoctest
//
//  Created by gump on 5/27/13.
//  Copyright (c) 2013 gump. All rights reserved.
//

#import "giftListDataBase.h"
#import "GiftListDataSource.h"
#import "giftlistDataInfo.h"

@implementation giftListDataBase

-(void)creatTable
{
    if (db == nil) {
        return;
    }
    
    pthread_mutex_lock(&mutexdatabase);
    
    [db open];
    
    [db executeUpdate:@"create table if not exists giftlistimage(giftid int,\
giftpath text)"];
    
    [db close];
    
    pthread_mutex_unlock(&mutexdatabase);
}

-(void)initData
{
        if (db == nil) {
            return;
        }
    
    pthread_mutex_lock(&mutexdatabase);
        
        [db open];
        
        NSString *strsql = [NSString stringWithFormat:@"SELECT * FROM giftlistimage"];
        FMResultSet *s = [db executeQuery:strsql];
        
        [[DataControl shareControl].giftlistDS delImageDic];
        
        while ([s next])
        {
            [[DataControl shareControl].giftlistDS InsertImageDicByID:[s intForColumn:@"giftid"]
                                                             withPath:[s stringForColumn:@"giftpath"]];
        }
        
        [db close];
    
    pthread_mutex_unlock(&mutexdatabase);
    
}

-(void)insertInfoByID:(int)iid withPath:(NSString *)strpath
{
    if (db == nil) {
        return;
    }
    
    pthread_mutex_lock(&mutexdatabase);
    
    [db open];
    
    NSString *strsql = [NSString stringWithFormat:@"SELECT * FROM giftlistimage where giftid = %d",iid];
    
    FMResultSet *s = [db executeQuery:strsql];
    
    if ([s next]) {
        strsql = [NSString stringWithFormat:@"update giftlistimage set giftpath = '%@'\
where giftid = %d",strpath,iid];
    }
    else
    {
        strsql = [NSString stringWithFormat:@"insert into giftlistimage \
(giftid,giftpath) \
values(%d,'%@')",iid,strpath];
    }
    
    [db executeUpdate:strsql];

    [db close];
    
    pthread_mutex_unlock(&mutexdatabase);

}

@end
